import turbogears   as tg

import logging
import cherrypy
import sqlobject
import kaizen

from sqlalchemy.exceptions import SQLError
from kaizen.model import Note, session
from kaizen.resource import Resource

from turbogears import identity, expose, validate, validators, redirect, error_handler, flash, view
from formencode import validators
from textile import textile

log = logging.getLogger("kaizen.subcontrollers.note")

class NoteController(Resource):
    @expose(template="kaizen.templates.viewNote", content_type='text/html; charset=utf-8')
    @error_handler()
    def load(self, post_id,  **keywords):
        log.info("load note " +post_id)
        note = session.get(Note, post_id)
        return dict(note=note, previousPage="kaizen.templates.viewNote")

    @expose(template="kaizen.templates.viewNote", content_type='text/html; charset=utf-8')

    @validate(validators={"title" : validators.NotEmpty()})
    @error_handler()
    def create(self, title, notes, tg_errors=None, **keywords):
        #if no title given
        if tg_errors:
            log.debug("no title")
            tg.flash("You must enter a title")
            return dict(tg_template="kaizen.templates.createNote")
        try:
          log.debug("new note. Title = " +title +".")
          note = Note(title=title, notes=notes)
          note.flush()
        except SQLError:
           tg.flash("Note already exists")
           return dict()
        tg.flash("Note added")
        kaizen.controllers.note_provider.update()
        return dict(note=note)


    @expose(allow_json=True, content_type='text/html; charset=utf-8')
    @validate(validators={"title" : validators.NotEmpty()})
    @error_handler()
    def save(self, title, notes, id, tg_errors=None, **keywords):
        #if no title given
        log.debug("notes=" +notes)
        if tg_errors:
            log.debug("no title")
            tg.flash("You must enter a title")
            return dict()
        #update
        try:
          note = session.get(Note,(int(id)))
          note.title=title
          note.notes=notes
          note.flush()
        except SQLError,x:
           log.error("error: ", x)
           tg.flash("Note already exists")
           return dict()
        tg.flash("Note updated")
        notes = textile(notes.encode('utf-8'), encoding='utf-8', output='ascii')
        return dict(success=True, notes=notes, title=title)

    @expose(template="kaizen.templates.welcome", content_type='text/html; charset=utf-8')
    @error_handler()
    def delete(self, id, **keywords):
        log.debug("delete Note " +id +".")
        note = session.get(Note,id)
        note.delete()
        note.flush()
        tg.flash("Note deleted")
        return dict()